package com.freedy.concurrent.Monitors.patterns;

/**
 * @author Freedy
 * @date 2021/4/22 13:27
 */
public class Guarded {
    private long id;
    //结果
    private Object response;

    public Guarded() {
    }

    public Guarded(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }

    public Object get(){
        return get(0);
    }

    /**
     * 获取结果
     * @param timeout 表示等待的超时时间。 当timeout为0时表示没有超时限制，即一直等待
     * @return 返回获取的结果 若等待超时则返回的为null
     */
    public Object get(long timeout){
        long begin = System.currentTimeMillis();
        long passedTime = 0;
        synchronized (this){
            while (response==null&&(passedTime<timeout||timeout==0)){
                try {
                    this.wait(timeout==0?0:(timeout-passedTime));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passedTime=System.currentTimeMillis()-begin;
            }
            return response;
        }
    }

    public void complete(Object response){
        synchronized (this){
            this.response=response;
            this.notifyAll();
        }
    }
}
